package customer

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	"gorm.io/gorm"
)

type gfyxCustomerPoolRepo struct {
	tenant_db.TenantDB
}

func NewGfyxCustomerPoolRepo() CustomerPoolRepoIface {
	return &gfyxCustomerPoolRepo{}
}

func (r *gfyxCustomerPoolRepo) Save(ctx context.Context, po *CustomerPoolPo) (*CustomerPoolPo, error) {
	err := r.GetTenantDB(ctx).Table(po.TableName()).Create(po).Error
	return po, err
}

func (r *gfyxCustomerPoolRepo) Query(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (int64, []*CustomerPoolPo, error) {
	db := r.GetTenantDB(ctx).Table(CustomerPoolPo{}.TableName()).Where("__IsDeleted = ?", constants.IsDeletedFalse)

	if companyNameList, ok := condition["CustomerNameList"]; ok {
		db.Where("CustomerName in (?)", companyNameList)
		delete(condition, "CustomerNameList")
	}
	if CreditCodeList, ok := condition["CreditCodeList"]; ok {
		db.Where("CreditCode in (?)", CreditCodeList)
		delete(condition, "CreditCodeList")
	}

	db = db.Where(condition)
	var count int64
	var queryList []*CustomerPoolPo
	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}

	if pageInfo != nil && pageInfo.Page > 0 && pageInfo.PageSize > 0 {
		db = db.Offset((pageInfo.Page - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize)
	}
	if err = db.Find(&queryList).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, nil, nil
		}
		return 0, nil, err
	}
	return count, queryList, nil
}

func (r *gfyxCustomerPoolRepo) Update(ctx context.Context, condition, updates map[string]interface{}) error {
	return r.GetTenantDB(ctx).Table(CustomerPoolPo{}.TableName()).Where(condition).Updates(updates).Error
}
